package com.hmall.search.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hmall.search.dto.searchfilters;
import com.hmall.search.mapper.SearchMapper;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.PageDTO;
import com.hmall.search.pojo.searchf;
import com.hmall.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @Description SearchServiceImpl
 * @Author liujiangyuan
 * @Date 2024-11-15-11:50
 */
@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Item> implements SearchService  {

@Autowired
private SearchMapper searchMapper;
    @Override
    public searchf searchfiter(searchfilters searchfilters) {
        List<Item> items = searchMapper.selectList(null);

        searchf searchf = new searchf();

        HashSet<String> categorys = new HashSet<>();
        HashSet<String> brands = new HashSet<>();
        for (Item item : items) {
            String category = item.getCategory();
            String brand = item.getBrand();
            categorys.add(category);
            brands.add(brand);
        }
        searchf.setCategory(categorys);
        searchf.setBrand(brands);

        return searchf;
    }

    @Override
    public PageDTO searchlist(searchfilters searchfilters) {
        PageHelper.startPage(searchfilters.getPage(),searchfilters.getSize());
        LambdaQueryWrapper<Item> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (searchfilters.getCategory()!= null &&!searchfilters.getCategory().isEmpty()) {
            lambdaQueryWrapper.eq(Item::getCategory, searchfilters.getCategory());
        }

        if (searchfilters.getBrand()!= null &&!searchfilters.getBrand().isEmpty()) {
            lambdaQueryWrapper.eq(Item::getBrand, searchfilters.getBrand());
        }
        if (searchfilters.getMinPrice()!= null) {
            lambdaQueryWrapper.ge(Item::getPrice, searchfilters.getMinPrice());
        }

        if (searchfilters.getMaxPrice()!= null) {
            lambdaQueryWrapper.le(Item::getPrice, searchfilters.getMaxPrice());
        }
        if (searchfilters.getSortBy()!= null&&searchfilters.getSortBy().equals("sold")) {
            lambdaQueryWrapper.orderByDesc(Item::getSold);
        }
        if (searchfilters.getSortBy()!= null&&searchfilters.getSortBy().equals("price")) {
            lambdaQueryWrapper.orderByDesc(Item::getPrice);
        }
        List<Item> items = searchMapper.selectList(lambdaQueryWrapper);

        PageInfo<Item> pageInfo=new PageInfo<>(items);
        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(pageInfo.getTotal());
        pageDTO.setList(items);
        return pageDTO;
    }
}
